/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufc.quixada.adrs.comandos.supervisor;

import br.ufc.quixada.adrs.interfaces.Comando;
import br.ufc.quixada.adrs.model.Supervisor;
import br.ufc.quixada.adrs.model.Usuario;
import br.ufc.quixada.adrs.service.SupervisorService;
import br.ufc.quixada.adrs.service.UsuarioService;
import br.ufc.quixada.adrs.util.Msg;
import br.ufc.quixada.adrs.util.UtilAdrs;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Franklin
 */
public class CmdSupervisorAlterarLogin implements Comando {

    public String executa(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Supervisor user = (Supervisor) session.getAttribute("user");

        String senhaAntiga = request.getParameter("senhaAntiga");
        String login = request.getParameter("login");
        String senha = request.getParameter("senha");
        String confSenha = request.getParameter("confSenha");

        Usuario u = new UsuarioService().getUsuarioByLogin(login);
        if (u != null && !login.equals(user.getUsuario().getLogin())) {
            session.setAttribute("erro", Msg.EXISTANT_LOGIN);
            return "/supervisor/supervisor_alterar_login.jsp";
        }
        if (senhaAntiga == null || login == null || senha == null || confSenha == null
                || senhaAntiga.trim() == null || login.trim() == null || senha.trim() == null
                || confSenha.trim() == null) {
            session.setAttribute("erro", Msg.REQUIRED_FIELDS);
            return "/supervisor/supervisor_alterar_login.jsp";
        }
        if (!UtilAdrs.criptografar(senhaAntiga).equals(user.getUsuario().getSenha())) {
            session.setAttribute("erro", Msg.WRONG_OLD_PASSWORD);
            return "/supervisor/supervisor_alterar_login.jsp";
        }
        if (senha.length() < 6) {
            session.setAttribute("erro", Msg.SHORT_NEW_PASSWORD);
            return "/supervisor/supervisor_alterar_login.jsp";
        }
        if (!senha.equals(confSenha)) {
            session.setAttribute("erro", Msg.PASSWORDS_DONT_MATCH);
            return "/supervisor/supervisor_alterar_login.jsp";
        }

        u = user.getUsuario();
        u.setLogin(login);
        u.setSenha(UtilAdrs.criptografar(senha));
        if (new UsuarioService().updateUsuario(u)) {
            session.setAttribute("sucesso", Msg.SUCCESSFULLY_EDITED);
            session.setAttribute("user", new SupervisorService().getSupervisorById(user.getId()));
            return "/supervisor/supervisor_index.jsp";
        } else {
            session.setAttribute("erro", Msg.OPERATIONAL_ERROR_EDITING);
            return "/supervisor/supervisor_alterar_login.jsp";
        }
    }
}
